<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-25 09:36
 * Modified Time: 2019-06-25 09:36
 * Version: 2.0
 */

namespace App\Modules\Employee\Services;

use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Exceptions\NotFoundException;
use App\Jobs\MessageQueue;
use App\Lib\Facades\FLAuth;
use App\Lib\Logs\Logs;
use App\Lib\Message\MessageJPush;
use App\Lib\Utilities;

use App\Modules\Employee\Criterias\GetBarberFansListCriteria;
use App\Modules\Employee\Criterias\GetEmployeeInfoCriteria;
use App\Modules\Employee\Criterias\getServiceListCriteria;
use App\Modules\Employee\Criterias\GetStoreUserListCriteria;
use App\Modules\Employee\Criterias\GetWxBarberInfoCriteria;
use App\Modules\Employee\Criterias\GetWxLikeBarberListCriteria;
use App\Modules\Employee\Criterias\GetWxNearbyNetRedCriteria;


use App\Modules\Employee\Repositories\EmployeeRoyaltyRepository;
use App\Modules\Employee\Repositories\SalaryRepository;
use App\Modules\Employee\Repositories\UserAccountRepository;
use App\Modules\Employee\Repositories\UserCoinRepository;
use App\Modules\Employee\Repositories\UserLikeRepository;
use App\Modules\Employee\Repositories\UserRankRepository;

use App\Modules\Message\Repositories\MessageRepository;
use App\Modules\Order\Repositories\OrderCommentRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Services\OrderService;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\System\Repositories\PictureRepository;
use App\Modules\System\Repositories\UserStoreRepository;

use App\Modules\Member\Repositoryies\MemberRepository;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Member\Repositoryies\ScheduleRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\RoleRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class EmployeeService extends BaseService
{
    /**
     * @var EmployeeRepository
     */
    private $employeeRepository;
    private $memberRepository;
    private $salaryRepository;
    private $userRankRepository;
    private $userCoinRepository;
    private $scheduleRepository;
    private $userLikeRepository;
    private $userStoreRepository;
    private $storeRepository;
    private $roleRepository;
    private $employeeRoyaltyRepository;
    private $serviceRepository;
    private $messageRepository;
    private $pictureRepository;
    private $userAccountRepository;
    private $orderCommentRepository;
    private $orderRepository;

    public function __construct(
        EmployeeRepository $employeeRepository,
        MemberRepository $memberRepository,
        SalaryRepository $salaryRepository,
        UserRankRepository $userRankRepository,
        UserCoinRepository $userCoinRepository,
        ScheduleRepository $scheduleRepository,
        StoreRepository $storeRepository,
        UserLikeRepository $userLikeRepository,
        UserStoreRepository $userStoreRepository,
        RoleRepository $roleRepository,
        ServiceRepository $serviceRepository,
        EmployeeRoyaltyRepository $employeeRoyaltyRepository,
        MessageRepository $messageRepository,
        PictureRepository $pictureRepository,
		UserAccountRepository $userAccountRepository,
		OrderCommentRepository $orderCommentRepository,
		OrderRepository $orderRepository
    )
    {
        $this->storeRepository = $storeRepository;
        $this->employeeRepository = $employeeRepository;
        $this->memberRepository = $memberRepository;
        $this->salaryRepository = $salaryRepository;
        $this->userRankRepository = $userRankRepository;
        $this->userCoinRepository = $userCoinRepository;
        $this->scheduleRepository = $scheduleRepository;
        $this->userLikeRepository = $userLikeRepository;
        $this->userStoreRepository = $userStoreRepository;
        $this->roleRepository = $roleRepository;
        $this->serviceRepository = $serviceRepository;
        $this->employeeRoyaltyRepository = $employeeRoyaltyRepository;
        $this->messageRepository = $messageRepository;
        $this->pictureRepository = $pictureRepository;
        $this->userAccountRepository = $userAccountRepository;
        $this->orderCommentRepository = $orderCommentRepository;
        $this->orderRepository = $orderRepository;
    }


    /**
     * app端用户注册
     * @param $mobile
     * @param $password
     * @return mixed
     */
    public function registerEmployee($mobile, $password)
    {
        $userInfo = $this->employeeRepository->register($mobile, $password);
        $this->userAccountRepository->add($userInfo->id);
        return $userInfo;
    }


    /**
     * App用户登录
     * @param $mobile
     * @param $password
     * @return mixed
     * @throws NotFoundException
     */
    public function loginEmployee($mobile, $password)
    {
        $userInfo = $this->employeeRepository->isExitedByMobile($mobile);
        if (empty($userInfo)) {
            throw new NotFoundException(["msg" => "该用户不存在"]);
        }
        if ($userInfo->password != $password) {
            throw new NotFoundException(["msg" => "用户名密码不匹配"]);
        }
        return $this->employeeRepository->updateToken($userInfo);
    }


    /**
     * 登录后获取的用户的店铺信息
     * @param $userId
     * @param null $storeId
     * @return mixed
     */
    public function getUserStoresInfo($userId, $storeId = null)
    {
        $roleStores = $this->userStoreRepository->roles($userId)->toArray();
        $res['store'] = null;
        if (!empty($roleStores)) {
            $res['store'] = $roleStores[0]['store'];
            foreach ($roleStores as $v) {
                if (empty($storeId)) {
                    if ($v['is_default']) {
                        $res['store'] = $v['store'];
                    }
                } else {
                    if ($v['sid'] == $storeId) $res['store'] = $v['store'];
                }
            }

            $res['role_store'] = Utilities::arrayColumnGroup($roleStores, null, 'rid');
        }
        //角色bool值
//        $res['role_bool'] = Utilities::getRoleBool($roleStores);
        $res['is_boss_barber'] = null;
        if (!empty($res['store'])) {
            $storeId = empty($storeId) ? $res['store']['id'] : $storeId;
            $ids = $this->userStoreRepository->roles($userId, $storeId)->toArray();
            $ids = array_unique(array_column($ids, 'rid'));
            $res['is_boss_barber'] = $this->roleRepository->getBossBarberControl($ids)->toArray();
        }
        return $res;
    }


    /**
     * 修改密码
     * @param $mobile
     * @param $newPassword
     * @return mixed
     * @throws NotFoundException
     */
    public function changePasswordUser($mobile, $newPassword)
    {
        $userInfo = $this->employeeRepository->isExitedByMobile($mobile);
        if (empty($userInfo)) {
            throw new NotFoundException(["msg" => "该用户不存在"]);
        }
        $userInfo = $this->employeeRepository->updatePassword($userInfo, $newPassword);
        $userInfo = $this->employeeRepository->updateToken($userInfo);

        return $userInfo['stores'] = $this->employeeRepository->getUserInfo($userInfo->id);
    }


    /**
     * 获取登录后用户的角色信息
     * @param $userId
     * @param int $storeId
     * @param int $roleType
     * @return mixed
     * @throws NotFoundException
     */
    public function getRoleInfo($userId, $storeId = 0, $roleType = 0)
    {
        $roleStores = $this->userStoreRepository->getRolesInfoByType($userId, $storeId)->toArray();
        if (empty($roleStores)) return [];
        $res['store_id'] = $storeId ? $storeId : $roleStores[0]['sid'];
        $res['is_default_store'] = 0;
        foreach ($roleStores as $v) {
            if (empty($storeId) && $v['is_default']) {
                $res['is_default_store'] = 1;
                $res['store_id'] = $v['sid'];
                $res['store_name'] = $v['store']['name'];
            } else {
                if ($res['store_id'] == $v['sid']) {
                    if ($v['is_default']) $res['is_default_store'] = 1;
                    $res['store_name'] = $v['store']['name'];
                }
            }
        }

        //角色bool值
//        $res['role_bool'] = Utilities::getRoleBool($roleStores);
        //校验角色值和切换的控制
        $roleList = config('constant.role');
        if (!in_array($roleType, $roleList)) {
            throw new NotFoundException(['msg' => '没有权限切换店铺或者角色']);
        }

        if ($res['store_id']) {
            $ids = $this->userStoreRepository->roles($userId, $res['store_id'])->toArray();
            $ids = array_unique(array_column($ids, 'rid'));
            $is_boss_barber = $this->roleRepository->getBossBarberControl($ids)->toArray();
        }

        if (count($is_boss_barber) == 1) {
            $res['is_barber'] = $is_boss_barber[0]['is_barber'];
            $res['is_boss'] = $is_boss_barber[0]['is_boss'];
        } else if (count($is_boss_barber) > 1) {
            $res['is_barber'] = 0;
            $res['is_boss'] = 0;
            foreach ($is_boss_barber as $v) {
                $res['is_barber'] = $res['is_barber'] | $v['is_barber'];
                $res['is_boss'] = $res['is_boss'] | $v['is_boss'];
            }
        } else {
            $res['is_barber'] = 0;
            $res['is_boss'] = 0;
        }

        return $res;
    }


    /**
     * 切换角色状态
     * @param $userId
     * @param $storeId
     * @param $roleType
     * @return mixed
     * @throws NotFoundException
     */
    public function isWorkedOpened($userId, $storeId, $roleType)
    {
        if ($roleType == config('constant.role.barber')) {
            $status = $this->isWorkedById($userId, $storeId);
        } else {
            $status = $this->isOpenByStoreId($storeId);
        }
        return $status;
    }


    /**
     * 店铺是否开业
     * @param $storeId
     * @return mixed
     * @throws NotFoundException
     */
    public function isOpenByStoreId($storeId)
    {
        $res = $this->storeRepository->isOpen($storeId);
        return empty($res) ? 0 : 1;
    }


    /**
     * 理发师是否上班
     * @param $userId
     * @param $storeId
     * @return int
     * @throws NotFoundException
     */
    public function isWorkedById($userId, $storeId)
    {
        $userStore = $this->userStoreRepository->isDefaultStore($userId, $storeId);
        if (empty($userStore)) {
            throw new NotFoundException(["msg" => "门店不存在！"]);
        };

        $isWorked = $this->scheduleRepository->isWorked($userId, $storeId);

        return empty($isWorked) ? ($userStore->is_default ? 1 : 0) : ($isWorked->status ? 1 : 0);
    }

    /**
     * 获取用户的基本信息
     * @param $userId
     * @return mixed
     * @author Happy dong
     * @modifiedTime 2019-07-31 13:54
     */
    public function getUserBaseInfo($userId)
    {
        return $this->employeeRepository->getUserBaseInfo($userId);
    }

    /*
     * 获取理发师信息
     */
    public function getEmployeeInfo($user_id,$store_id)
    {
        if($store_id===null){
            $store_id = $this->userStoreRepository->getUserPermanentStore($user_id)->sid;
        }
        return $this->employeeRepository->pushCriteria(new GetEmployeeInfoCriteria($user_id,$store_id))->first();
    }


	/**
	 * 县令币余额
	 * @param $userId
	 * @return array
	 * @throws NotFoundException
	 */
    public function getBarberCoinInfo($userId){
    	$coin =  $this->employeeRepository->getUserCoinInfo($userId);
    	return ['status'=>1,'msg'=>'获取县令币余额成功！','data'=>$coin];
    }



    /*
     * 修改理发师信息
     */
    public function updateEmployeeInfo($user_id, $nick, $portrait, $introduction, $mobile, $wechat)
    {
        return $this->employeeRepository->updateEmployeeInfo($user_id, $nick, $portrait, $introduction, $mobile, $wechat);
    }

	/**
	 * 添加新的理发师到店铺
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 * @throws AllValidatorException
	 * @throws DbException
	 * @throws NotFoundException
	 */
    public function AddNewBarber($userId, $storeId)
    {
        // 查询理发师是否注册
        $this->employeeRepository->isExited($userId);
        // 查询店铺是否存在
        $this->storeRepository->isExited($storeId);
        // 查询该店铺是否已经注册该理发师
        $userStore = $this->userStoreRepository->getRolesInfoByType($userId, $storeId, config('constant.role.barber'));

        // 判断当前用户是否已经加入过当前店铺
        if (!$userStore->isEmpty()) {
            throw new AllValidatorException((['msg' => '该理发师已经是本店铺理发师！请勿重复添加']));
        };
        $isExitedStore = $this->userStoreRepository->getRolesInfoByType($userId, 0, config('constant.role.barber'));
        $isDefault = $isExitedStore->isEmpty() ? 1 : 0;
        //插入默认提成
        $service = $this->serviceRepository->getStoreServiceArray($storeId);

        $service_royalty = [];

        foreach ($service as $key => $value) {
            $service_royalty[$key]['service_id'] = $value['id'];
            $service_royalty[$key]['royalty'] = $value['royalty'];
            $service_royalty[$key]['store_id'] = $storeId;
            $service_royalty[$key]['status'] = 1;
            $service_royalty[$key]['assistant_royalty'] = $value['assistant_royalty'];
        }

        $this->setBarberRoyalty($userId, $storeId, 0, $service_royalty);
        // 插入中间表的数据
        return $this->userStoreRepository->addBarber($userId, $storeId, $isDefault);
    }


    /**
     * 设置理发师的日程表
     * @param $barberId
     * @param $storeId
     * @param $workDays
     * @return mixed
     * @throws NotFoundException
     * @author Happy dong
     * @modifiedTime 2019-08-07 14:45
     */
    public function setWorkDay($barberId, $storeId, $date, $days)
    {
        DB::beginTransaction();
        try{
            $isDefault = $this->employeeRepository->isDefaultByStoreId($barberId, $storeId);

            $data = array_map(function ($v) use ($isDefault, $date, $barberId, $storeId) {
                return [
                    'user_id' => $barberId,
                    'store_id' => $storeId,
                    'status' => $isDefault ? 0 : 1,
                    'plan_date' => strtotime($date . '-' . $v),
                ];
            }, $days);
            $this->scheduleRepository->deleteByDate($barberId, $storeId, $date);
            $create = $this->scheduleRepository->createAll($data);

            //发消息
            $storeInfo = $this->storeRepository->isExited($storeId);
            $barber = $this->getEmployeeInfo($barberId,$storeId);
            $barber_name = $barber->nick;
            $barber_face = $barber->portrait;
            $scene =  config('constant.message.scene.app');
            $type = config('constant.message.sub_type.barber_schedule');
            $content = '我修改了排班，请老板审阅。';
            $noticeFace = $barber_face;
            $noticeTitle = $barber_name;
            $noticeTitleRight = $storeInfo->name;;
            $contentLeft = '我修改了排班，请老板审阅。';
            $contentRight = "";
            $datas = $this->messageRepository->makeMessageData($scene,$type,$noticeFace,$noticeTitle,$noticeTitleRight,$contentLeft,$contentRight,$content);
	        $this->messageRepository->sendBossMessage(config('constant.role.manager'), $storeId, $datas,$barberId);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            throw new DbException();
        }
	    return $create;

    }


    public function getScheduleByMonth($barberId, $storeId, $date)
    {
        $days = date('t', strtotime($date));
        $startTime = $date . '-01';
        $endTime = $date . '-' . $days;
        return $this->scheduleRepository->getScheduleList($storeId, $startTime, $endTime, $barberId);
    }


    public function getStoreRestList($storeId, $date = null,$isBoss=true)
    {
        $date = empty($date) ? date('Y-m', time()) : $date;
        $days = date('t', strtotime($date));
        $startTime = $date . '-01';
        $endTime = $date . '-' . $days;

        return $this->scheduleRepository->getScheduleList($storeId, $startTime, $endTime, null, config('constant.no'));
    }




    /**
     * 设置用户提成
     */
    public function setBarberRoyalty($userId, $storeId, $salary, $royalty)
    {
        DB::beginTransaction();
        //设置基本工资
        try {
	        $this->userStoreRepository->setBaseSalary($storeId,$userId,$salary);
	        $this->employeeRoyaltyRepository->delBarber($storeId, $userId);
            foreach ($royalty as $key => $value) {
                //判断服务是否存在
                $isExisted = $this->serviceRepository->isExisted($value['service_id'],true);
                if($isExisted){
                    $service_id = $value['service_id'];
                    $royalty = $value['royalty'];
//                    助理提成独立
//                    $assistant_royalty = $value['assistant_royalty'];
                    $assistant_royalty = 0;
                    $status = isset($value['status']) ? $value['status'] : 1;
                    $this->employeeRoyaltyRepository->setRoyalty($userId, $storeId, $service_id, $royalty, $assistant_royalty, $status);
                }
           }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new DbException();
        }
    }


    /**
     * 获取理发师的薪水详情
     * @param $requestData
     * @return mixed
     */
    public function getMySalaryInfo($requestData)
    {
        return $this->salaryRepository->getMySalaryInfo($requestData);
    }

    /**
     * 定时任务 写入数据库 理发师排名
     * @return bool|mixed
     * @throws ValidatorException
     */
//	public function userRank()
//	{
//		return $this->salaryRepository->userRank();
//	}

    /**
     * 获取理发师排名
     * @param $requestData
     * @return mixed
     */
    public function getUserRank($requestData)
    {
        return $this->userRankRepository->getUserRank($requestData);
    }

    /**
     * 查询剪发师的某天的积分数
     * @param $requestData
     * @return mixed
     */
    public function getUserCoinDay($requestData)
    {
        return $this->userCoinRepository->getUserCoinDay($requestData);
    }

	/**
	 * 理发师工资定时任务写数据库
	 * @return mixed
	 * @throws NotFoundException
	 */
    public function barberSalaryAdd($date=null)
    {
	    // 获取所有店铺的id
	    $storeIds = $this->storeRepository->getStoreAllIds();
	    // 计算前一天的工资
	    $date = empty($date)  ? date('Y-m-d',strtotime('-1 day')) : $date;
	    // 计算某店铺的员工工资列表
	    $peopleSalary = array_map(function($v) use($date){
		    return $this->orderRepository->storeSalaryList($v, $date);
	    },$storeIds);

	    $peopleSalary = array_filter($peopleSalary,function($v){
		    return (!empty($v));
	    });

	    if(empty($peopleSalary)){
		    $msg = '理发师工资计算结果信息为空';
		    Logs::info( $msg.'时间'.date('Y-m-d H:i:s',time()));
		    throw new NotFoundException(['msg'=>$msg]);
	    }

	    $result =array_map(function($v){
		    // 插入数据操作
		    $res = $this->salaryRepository->add($v);
		    $res ? '' : Logs::info('理发店铺ID号为'.array_column($v,'store_id').'人员工资插入异常！请手动修复！ 时间：'.date('Y-m-d H:i:s', time()));
		    return $res;
	    },$peopleSalary);
	    // 处理返回操作的bool值
	    return  array_reduce($result,function($v,$v2){
		    return  $v = $v&&$v2;
	    },true);
    }

    /*
     * 用户关注理发师
     */
    public function likeUser($requestData)
    {
        $data_rule = [
            'user_id' => '缺少理发师id',
            'operation' => '缺少操作值',
            'store_id' => '缺少店铺id'
        ];

        Utilities::checkRequestDataKeyExist($requestData, $data_rule);

        $operation = $requestData['operation'];
        $user_id = $requestData['user_id'];
        $store_id = $requestData['store_id'];

        $member_id = FLAuth::id();;

        $data = [
            'member_id' => $member_id,
            'user_id' => $user_id,
            'store_id' => $store_id,
        ];

        if ($operation == 1) {//关注

            $this->userLikeRepository->firstOrCreate($data);

        } elseif ($operation == 0) {//取消关注
            $this->userLikeRepository->deleteUserLike($member_id,$user_id,$store_id);
        } else {
            throw new AllValidatorException(['msg' => '操作值有误']);
        }
    }

	/**
	 * 获取某店下所有理发师列表
	 * @param $storeId
	 * @return mixed
	 * @throws NotFoundException
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
    public function getStoreUserList($storeId)
    {
        $this->storeRepository->isExited($storeId);
        $list = $this->userStoreRepository->pushCriteria(new GetStoreUserListCriteria($storeId))->get();
        return $list;
    }

	/**
	 * 理发师详情
	 * @param $requestData
	 * @return array
	 * @throws NotFoundException
	 */
    public function getBarBerInfo($requestData)
    {

        $params = [
            'member_id' => FLAuth::id(),
            'user_id' => $requestData['barber_id']
        ];
        $isLike = $this->userLikeRepository->findWhere($params)->first();
        $this->storeRepository->isExited($requestData['store_id']);
        $userInfo = $this->employeeRepository->getUserInfoByStoreIdDetails($requestData['store_id'],$requestData['barber_id']);
        $res_data = [
            'status' => 1
        ];
        if (!$userInfo->id) {//理发师不存在 查找其他常驻店
            $store_id = $this->userStoreRepository->getUserPermanentStore($requestData['barber_id'])->sid;
            if ($store_id) {
                $res_data['status'] = 0;
                $res_data['store_id'] = $store_id;
            } else {
                $res_data['status'] = -1;
            }
        }
        if ($userInfo) {
        	$userInfo->portrait = isset($userInfo->picture->image) ? $userInfo->picture->image : "";
        	$stores = isset($userInfo->userStore) ? $userInfo->userStore->toArray(): [];
        	$userInfo->store = isset($stores[0]['store']) ?  $stores[0]['store'] : '';
        	if(!empty($userInfo->store)){
        		$userInfo->scores = $this->orderCommentRepository->getBarberCommentScore($requestData['store_id'],$requestData['barber_id']);
	        }
        	unset($userInfo->picture);
        	unset($userInfo->userStore);

//            //@todo 待实现
//	        $userInfo->bg_img = 'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1563262725&di=93d7aeda691fbc8c282022aadf938e9a&src=http://img2.ph.126.net/b4MDUQVUfIldL-bYPWks_A==/616430199013734992.jpg';
	        $userInfo->isLike = empty($isLike) ? 0 : 1;
        }
        $res_data['data'] = $userInfo;
        return $res_data;
    }

    /**
     * 获取某理发师某店铺的服务
     * @param $barberId
     * @param $storeId
     * @return mixed
     * @throws NotFoundException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function serviceList($barberId,$storeId,$status=1)
    {
        $this->storeRepository->isExited($storeId);
        if(!empty($barberId)){
	        $this->employeeRepository->isExited($barberId);
        }
        return $this->employeeRoyaltyRepository->getServiceListByStoreIdAndUserId($barberId,$storeId,$status);
    }

    /**
     * 获取网红理发师排名
     * @param $requestData
     * @return array|mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     * @author Happy dong
     * @modifiedTime 2019-08-09 17:44
     */
    public function getNearbyNetRedList($member_id,$adcode,$pageSize)
    {
        $list = $this->employeeRepository
            ->pushCriteria(new GetWxNearbyNetRedCriteria($member_id,$adcode))
            ->paginate($pageSize, ['*'], 'paginate');
        $list = Utilities::dealPage($list);
        return $list;
    }

    /**
     * @param $requestData
     * @return array|mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     * @author Happy dong
     * @modifiedTime 2019-08-09 17:44
     */
    public function getLikeBarberList($requestData)
    {
        $pageSize = isset($requestData['pageSize']) ? $requestData['pageSize'] : 5;
        $requestData['member_id'] = FLAuth::id();
        $list = $this->employeeRepository->pushCriteria(new GetWxLikeBarberListCriteria($requestData))
            ->paginate($pageSize, ['*'], 'paginate');
        $list = Utilities::dealPage($list);;
        return $list;
    }


    /**
     * 获根据角色取店铺列表
     * @param $userId
     * @param $roleType
     * @return array|mixed
     */
    public function getStoreListByRoleType($userId, $roleType)
    {
        $result = $this->userStoreRepository->getStoresByUserIdRoleType($userId, $roleType);
        return empty($result) ? [] : $result;
    }


    public function getStoreListByUserId($userId){
	    $storeList = $this->userStoreRepository->getStoresByUserId($userId);
		$storeList = empty($storeList) ? [] : array_map(function ($v){
			return $v['store'];
		},$storeList);
		return $storeList;
    }

    public function getRoleListByStoreIdUserId($storeId,$userId){
	    $roleList = $this->userStoreRepository->getRoleListByStoreIdUserId($storeId,$userId);
	    $roleList = empty($roleList) ? [] : array_map(function ($v){
		    return $v['role'];
	    },$roleList);
	    return $roleList;
    }

    public function getModuleByRoleId($roleId){
    	$moduleList = $this->roleRepository->getModuleListByRoleId($roleId);
    	return isset($moduleList['module']) ? $moduleList['module'] : [];
    }

    /**
     * 获取店铺理发师列表
     * @param $storeId
     * @param int $pageSize
     * @return array
     * @throws NotFoundException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getStoreBarberList($storeId, $pageSize = 0)
    {
        $this->storeRepository->isExited($storeId);
        return $this->employeeRepository->getStoreBarberList($storeId, $pageSize);
    }

    /**
     * 获取理发师提成设置
     * @param $storeId
     * @param $userId
     * @return mixed
     * @throws NotFoundException
     */
    public function getBarberRoyaltySet($storeId, $userId)
    {
        $this->storeRepository->isExited($storeId);
        $this->employeeRepository->isExited($userId);
//		return $this->employeeRoyaltyRepository->getBarberRoyaltySet();
        return $this->serviceRepository->getBarberRoyaltySet($storeId, $userId);
    }


    /**
     * 通过角色获取用户信息
     * @param $role
     * @param $storeId
     * @return UserStoreRepository[]|\Illuminate\Database\Eloquent\Collection
     * @throws NotFoundException
     */
    public function getUserInfoByRole($role, $storeId, $selfId, $have_self = '1')
    {
        $this->storeRepository->isExited($storeId);
        return $this->userStoreRepository->getUserInfoByRoleAndStoreId($role, $storeId,$selfId,$have_self == '1');
    }

    public function getEmployeeProfile($user_id)
    {
        $data = $this->employeeRepository->getEmployeeProfile($user_id);
        $res_data = [
            'picture' => [
                'id' => $data['profile_picture_id'],
                'image' => $data['profile_picture']
            ],
            'video' => [
                'id' => $data['profile_video_id'],
                'thumb' => $data['thumb'],
                'url' => $data['profile_video']
            ]
        ];
        return $res_data;
    }

    public function updateEmployeeProfile($user_id, $profile_picture, $profile_video)
    {
        return $this->employeeRepository->updateEmployeeProfile($user_id, $profile_picture, $profile_video);
    }

    /**
     * OSS方式更新用户头像
     * @param $user_id
     * @param $oss_url
     * @throws
     */
    public function updateEmployeePortrait($user_id, $oss_url)
    {
        DB::beginTransaction();
        try {
            // 创建图片资源
            $image_id = $this->pictureRepository->add("", $oss_url);
            // 更新门店logo
            $this->employeeRepository->updatePortrait($user_id, $image_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new DbException();
        }
    }

    /**
     * 删除理发师
     * @param $store_id
     * @param $user_id
     */
    public function delBarber($store_id, $user_id)
    {
        DB::beginTransaction();
        try {
            $this->userStoreRepository->delBarber($store_id, $user_id);
            $this->employeeRoyaltyRepository->delBarber($store_id, $user_id);
            return DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new DbException();
        }

    }

    /**
     * 获取理发师粉丝
     * @param $user_id
     * @param $pageSize
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getBarberFansList($user_id,$store_id, $pageSize)
    {
        $data = $this->userLikeRepository
            ->pushCriteria(new GetBarberFansListCriteria($user_id,$store_id))
            ->paginate($pageSize, ['*']);
        return Utilities::dealPage($data);
    }

    /**
     * 获取理发师今日粉丝数
     */
    public function getTodayBarberFansNum($user_id,$store_id)
    {
        $date = date('Y-m-d',time());
        return $this->userLikeRepository->getBarberDateFansNum($user_id,$store_id,$date);

    }

	/**
	 * 排班任务
	 * @return bool
	 */
    public function rewriteSchedule(){
    	// 排班
	    return $this->scheduleRepository->rewriteAll();
    }


	/**
	 * 查询用户在店铺的角色列表和获取当前默认角色
	 * @param $storeId
	 * @param $userId
	 * @param $roleType
	 * @return array
	 * @throws NotFoundException
	 */
    public function getUserStoreRoleList($storeId,$userId,$roleType){
	    $roleList = $this->getRoleListByStoreIdUserId($storeId,$userId);
	    $defaultRoleType = isset($roleList[0]['id']) ? $roleList[0]['id'] : 0;
	    $currentRoleType = $roleType ?  $roleType : $defaultRoleType;
	    if(empty($roleList)){
		    throw new NotFoundException(['msg'=>'对不起，您在本店没有角色权限']);
	    }else{
		    $roleIds = array_column($roleList,'id');
		    if(!in_array($currentRoleType,$roleIds)){
			    throw new NotFoundException(['msg'=>'对不起，您在本店没有当前角色权限，请切换其他角色权限']);
		    }
	    }
	    return compact('roleList','currentRoleType');
    }


	/**
	 * 检测理发师和店铺服务的匹配
	 * @param $serviceId
	 * @param $userId
	 * @param $storeId
	 * @return bool
	 * @throws NotFoundException
	 */
    public function checkBarberHasSkill($serviceId,$userId,$storeId){
    	Log::info('check_barber_skill');
	    $serviceInfo = $this->serviceRepository->isExisted($serviceId);
	    if ($serviceInfo->store_id != $storeId) {
		    throw new NotFoundException(['msg' => '店铺和服务不匹配，请修正后重新发起预约']);
	    }
		$info = $this->employeeRoyaltyRepository->checkBarberServiceIsSuited($userId,$serviceId,$storeId);
	    if(empty($info)){
	    	throw new NotFoundException(['msg' => '理发师和服务不匹配！']);
	    }
	    return true;
    }


	/**
	 * 县令币消费
	 * @param $userId
	 * @param $coin
	 * @return array
	 */
    public function consumedCoin($userId,$coin){
    	$userInfo =$this->employeeRepository->find($userId);
    	if($userInfo->coin < $coin) return ['status'=>0,'msg'=>'县令币余额不足，请先充值！'];
    	$userInfo->coin -= $coin;
    	$userInfo->save();
    	return ['status'=>1,'msg'=>'县令币扣除成功'];
    }
}
